<!DOCTYPE html>













<html class="theme-next gemini" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.4.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  





  <meta name="description" content="字符串传递Python提供了几种不同方式传递的字符串。它们用单引号或双引号标识:&amp;gt;&amp;gt;&amp;gt; &amp;apos;spam eggs&amp;apos;&amp;apos;spam eggs&amp;apos;&amp;gt;&amp;gt;&amp;gt; &amp;apos;doesn\&amp;apos;t&amp;apos;&amp;quot;doesn&amp;apos;t&amp;quot;&amp;gt;&amp;gt;&amp;gt; &amp;quot;doesn&amp;apos;t&amp;quot;&amp;quot;">
<meta name="keywords" content="Oier, Student, China, Algorithm">
<meta property="og:type" content="article">
<meta property="og:title" content="Python字符串">
<meta property="og:url" content="https://sshwy.gitee.io/2018/10/01/35224/index.html">
<meta property="og:site_name" content="Sailor&#39;s Blog">
<meta property="og:description" content="字符串传递Python提供了几种不同方式传递的字符串。它们用单引号或双引号标识:&amp;gt;&amp;gt;&amp;gt; &amp;apos;spam eggs&amp;apos;&amp;apos;spam eggs&amp;apos;&amp;gt;&amp;gt;&amp;gt; &amp;apos;doesn\&amp;apos;t&amp;apos;&amp;quot;doesn&amp;apos;t&amp;quot;&amp;gt;&amp;gt;&amp;gt; &amp;quot;doesn&amp;apos;t&amp;quot;&amp;quot;">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-11-17T15:41:31.890Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python字符串">
<meta name="twitter:description" content="字符串传递Python提供了几种不同方式传递的字符串。它们用单引号或双引号标识:&amp;gt;&amp;gt;&amp;gt; &amp;apos;spam eggs&amp;apos;&amp;apos;spam eggs&amp;apos;&amp;gt;&amp;gt;&amp;gt; &amp;apos;doesn\&amp;apos;t&amp;apos;&amp;quot;doesn&amp;apos;t&amp;quot;&amp;gt;&amp;gt;&amp;gt; &amp;quot;doesn&amp;apos;t&amp;quot;&amp;quot;">






  <link rel="canonical" href="https://sshwy.gitee.io/2018/10/01/35224/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Python字符串 | Sailor's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Sailor's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Amorphophalms konjac Oier</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-links">
    <a href="/links/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />友情链接</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://sshwy.gitee.io/2018/10/01/35224/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sshwy">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sailor's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Python字符串
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-01 20:22:00" itemprop="dateCreated datePublished" datetime="2018-10-01T20:22:00+08:00">2018-10-01</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-11-17 23:41:31" itemprop="dateModified" datetime="2018-11-17T23:41:31+08:00">2018-11-17</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/程序语言/" itemprop="url" rel="index"><span itemprop="name">程序语言</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="字符串传递"><a href="#字符串传递" class="headerlink" title="字符串传递"></a>字符串传递</h1><p>Python提供了几种不同方式传递的字符串。它们用<strong>单引号或双引号</strong>标识:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; &apos;spam eggs&apos;</span><br><span class="line">&apos;spam eggs&apos;</span><br><span class="line">&gt;&gt;&gt; &apos;doesn\&apos;t&apos;</span><br><span class="line">&quot;doesn&apos;t&quot;</span><br><span class="line">&gt;&gt;&gt; &quot;doesn&apos;t&quot;</span><br><span class="line">&quot;doesn&apos;t&quot;</span><br><span class="line">&gt;&gt;&gt; &apos;&quot;Yes,&quot; he said.&apos;</span><br><span class="line">&apos;&quot;Yes,&quot; he said.&apos;</span><br><span class="line">&gt;&gt;&gt; &quot;\&quot;Yes,\&quot; he said.&quot;</span><br><span class="line">&apos;&quot;Yes,&quot; he said.&apos;</span><br><span class="line">&gt;&gt;&gt; &apos;&quot;Isn\&apos;t,&quot; she said.&apos;</span><br><span class="line">&apos;&quot;Isn\&apos;t,&quot; she said.&apos;</span><br></pre></td></tr></table></figure></p>
<p>Python解释器按照字符串被输入的方式打印字符串结果：为了显示准确的值，字符串包含在<strong>成对的引号</strong>中，引号和其他特殊字符要用反斜线（\\）转译。 如果字符串只包含单引号（’）而没有双引号（”）就可以用双引号（”）包围，反之用单引号（’）包围。 <strong>再强调一下，print函数可以生成可读性更好的输出。</strong></p>
<h1 id="分行"><a href="#分行" class="headerlink" title="分行"></a>分行</h1><p>字符串文本有几种方法分行。可以使用<strong>反斜杠为行结尾</strong>的连续字符串，它表示下一行在逻辑上是本行的后续内容:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">hello = &quot;This is a rather long string containing\n\</span><br><span class="line">several lines of text just as you would do in C.\n\</span><br><span class="line">    Note that whitespace at the beginning of the line is\</span><br><span class="line"> significant.&quot;</span><br><span class="line"></span><br><span class="line">print(hello)</span><br></pre></td></tr></table></figure></p>
<p>需要注意的是，<strong>还是需要在字符串中写入\\n</strong> ——结尾的反斜杠会被忽略。前例会打印为如下形式:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">This is a rather long string containing</span><br><span class="line">several lines of text just as you would do in C.</span><br><span class="line">    Note that whitespace at the beginning of the line is significant.</span><br></pre></td></tr></table></figure></p>
<p>另外，字符串可以标识在一对儿三引号中：<code>&quot;&quot;&quot;</code>或<code>&#39;&#39;&#39;</code>。<strong>三引号中，不需要行属转义</strong>，它们已经包含在字符串中。<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">print(&quot;&quot;&quot;\</span><br><span class="line">Usage: thingy [OPTIONS]</span><br><span class="line">     -h                        Display this usage message</span><br><span class="line">     -H hostname               Hostname to connect to</span><br><span class="line">&quot;&quot;&quot;)</span><br></pre></td></tr></table></figure></p>
<p>得到如下输出:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Usage: thingy [OPTIONS]</span><br><span class="line">     -h                        Display this usage message</span><br><span class="line">     -H hostname               Hostname to connect to</span><br></pre></td></tr></table></figure></p>
<p>如果我们生成一个<strong>“原始”字符串</strong>， \\n 序列不会被转义，而且行尾的反斜杠，源码中的换行符，都成为字符串中的一部分数据，因此下例:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">hello = r&quot;This is a rather long string containing\n\</span><br><span class="line">several lines of text much as you would do in C.&quot;</span><br><span class="line"></span><br><span class="line">print(hello)</span><br></pre></td></tr></table></figure></p>
<p>会打印:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">This is a rather long string containing\n\</span><br><span class="line">several lines of text much as you would do in C.</span><br></pre></td></tr></table></figure></p>
<h1 id="连接与重复"><a href="#连接与重复" class="headerlink" title="连接与重复"></a>连接与重复</h1><p>字符串可以由 + 操作符连接（粘到一起），可以由 * 重复:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; word = &apos;Help&apos; + &apos;A&apos;</span><br><span class="line">&gt;&gt;&gt; word</span><br><span class="line">&apos;HelpA&apos;</span><br><span class="line">&gt;&gt;&gt; &apos;&lt;&apos; + word*5 + &apos;&gt;&apos;</span><br><span class="line">&apos;&lt;HelpAHelpAHelpAHelpAHelpA&gt;&apos;</span><br></pre></td></tr></table></figure></p>
<p><strong>相邻的两个字符串文本自动连接在一起</strong>，前面那行代码也可以写为 word =’Help’ ‘A’<br>它只用于两个字符串<strong>文本</strong>，不能用于字符串<strong>表达式</strong>:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; &apos;str&apos; &apos;ing&apos;                   #  &lt;-  This is ok</span><br><span class="line">&apos;string&apos;</span><br><span class="line">&gt;&gt;&gt; &apos;str&apos;.strip() + &apos;ing&apos;   #  &lt;-  This is ok</span><br><span class="line">&apos;string&apos;</span><br><span class="line">&gt;&gt;&gt; &apos;str&apos;.strip() &apos;ing&apos;     #  &lt;-  This is invalid</span><br><span class="line">  File &quot;&lt;stdin&gt;&quot;, line 1, in ?</span><br><span class="line">    &apos;str&apos;.strip() &apos;ing&apos;</span><br><span class="line">                      ^</span><br><span class="line">SyntaxError: invalid syntax</span><br></pre></td></tr></table></figure></p>
<h1 id="检索"><a href="#检索" class="headerlink" title="检索"></a>检索</h1><p>字符串也可以被截取（检索）。类似于 C ，字符串的第一个字符索引为 0 。<strong>没有独立的字符类型</strong>，字符就是长度为 1 的字符串。类似 Icon ，可以用<strong>切片标注法</strong>截取字符串：由两个索引分割的复本。<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; word[4]</span><br><span class="line">&apos;A&apos;</span><br><span class="line">&gt;&gt;&gt; word[0:2]</span><br><span class="line">&apos;He&apos;</span><br><span class="line">&gt;&gt;&gt; word[2:4]</span><br><span class="line">&apos;lp&apos;</span><br></pre></td></tr></table></figure></p>
<p>索引切片可以有默认值，切片时，<strong>忽略第一个索引的话，默认为0，忽略第二个索引，默认为字符串的长度</strong>。<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; word[:2]    # The first two characters</span><br><span class="line">&apos;He&apos;</span><br><span class="line">&gt;&gt;&gt; word[2:]    # Everything except the first two characters</span><br><span class="line">&apos;lpA&apos;</span><br></pre></td></tr></table></figure></p>
<p>不同于 C 字符串，<strong>Python字符串不可变（常量）</strong>。向字符串文本的某一个索引赋值会引发错误:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; word[0] = &apos;x&apos;</span><br><span class="line">Traceback (most recent call last):</span><br><span class="line">  File &quot;&lt;stdin&gt;&quot;, line 1, in ?</span><br><span class="line">TypeError: &apos;str&apos; object does not support item assignment</span><br><span class="line">&gt;&gt;&gt; word[:1] = &apos;Splat&apos;</span><br><span class="line">Traceback (most recent call last):</span><br><span class="line">  File &quot;&lt;stdin&gt;&quot;, line 1, in ?</span><br><span class="line">TypeError: &apos;str&apos; object does not support slice assignment</span><br></pre></td></tr></table></figure></p>
<p>不过，组合文本内容生成一个新文本简单而高效:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; &apos;x&apos; + word[1:]</span><br><span class="line">&apos;xelpA&apos;</span><br><span class="line">&gt;&gt;&gt; &apos;Splat&apos; + word[4]</span><br><span class="line">&apos;SplatA&apos;</span><br></pre></td></tr></table></figure></p>
<p>切片操作有个有用的不变性：<strong>s[:i] + s[i:] 等于 s</strong>。<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; word[:2] + word[2:]</span><br><span class="line">&apos;HelpA&apos;</span><br><span class="line">&gt;&gt;&gt; word[:3] + word[3:]</span><br><span class="line">&apos;HelpA&apos;</span><br></pre></td></tr></table></figure></p>
<p>Python能够优雅的处理那些<strong>没有意义的切片索引</strong>：一个过大的索引值（即下标值大于字符串实际长度）将被字符串实际长度所代替，当上边界比下边界大时（即切片左值大于右值）就返回空字符串。<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; word[1:100]</span><br><span class="line">&apos;elpA&apos;</span><br><span class="line">&gt;&gt;&gt; word[10:]</span><br><span class="line">&apos;&apos;</span><br><span class="line">&gt;&gt;&gt; word[2:1]</span><br><span class="line">&apos;&apos;</span><br></pre></td></tr></table></figure></p>
<p>索引也可以是负数，这将导致从右边开始计算。 例如:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; word[-1]     # The last character</span><br><span class="line">&apos;A&apos;</span><br><span class="line">&gt;&gt;&gt; word[-2]     # The last-but-one character</span><br><span class="line">&apos;p&apos;</span><br><span class="line">&gt;&gt;&gt; word[-2:]    # The last two characters</span><br><span class="line">&apos;pA&apos;</span><br><span class="line">&gt;&gt;&gt; word[:-2]    # Everything except the last two characters</span><br><span class="line">&apos;Hel&apos;</span><br></pre></td></tr></table></figure></p>
<p>请注意 -0 实际上就是 0 ，所以它不会导致从右边开始计算！<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; word[-0]     # (since -0 equals 0)</span><br><span class="line">&apos;H&apos;</span><br></pre></td></tr></table></figure></p>
<p>负索引切片越界会被截断，不要尝试将它用于单元素（非切片）检索:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; word[-100:]</span><br><span class="line">&apos;HelpA&apos;</span><br><span class="line">&gt;&gt;&gt; word[-10]    # error</span><br><span class="line">Traceback (most recent call last):</span><br><span class="line">  File &quot;&lt;stdin&gt;&quot;, line 1, in ?</span><br><span class="line">IndexError: string index out of range</span><br></pre></td></tr></table></figure></p>
<p>有个办法可以很容易的记住切片的工作方式：切片时的索引是在两个字符 之间 。左边第一个字符的索引为0，，而长度为 n 的字符串其最后一个字符的右界索引为 n 。例如:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line"> +---+---+---+---+---+</span><br><span class="line"> | H | e | l | p | A |</span><br><span class="line"> +---+---+---+---+---+</span><br><span class="line"> 0   1   2   3   4   5</span><br><span class="line">-5  -4  -3  -2  -1</span><br></pre></td></tr></table></figure></p>
<p>文本中的第一行数字给出字符串中的索引点 0…5 。第二行给出相应的负索引。切片是从 i 到 j 两个数值标示的边界之间的所有字符。</p>
<p>对于非负索引，如果上下都在边界内，切片长度与索引不同。例如， word[1:3] 是 2 。</p>
<h1 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h1><p>内置函数 <strong>len()</strong> 返回字符串长度:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; s = &apos;supercalifragilisticexpialidocious&apos;</span><br><span class="line">&gt;&gt;&gt; len(s)</span><br><span class="line">34</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<h1 id="关于Unicode"><a href="#关于Unicode" class="headerlink" title="关于Unicode"></a>关于Unicode</h1><p>从Python 3.0开始所有的字符串都支持Unicode（参考 <a href="http://www.unicode.org" target="_blank" rel="noopener">http://www.unicode.org</a> ）。</p>
<p>Unicode的先进之处在于为每一种现代或古代使用的文字系统中出现的每一个字符都提供了统一的序列号。之前，文字系统中的字符只能有 256 种可能的顺序。通过代码页分界映射。文本绑定到映射文字系统的代码页。这在软件国际化的时候尤其麻烦 （通常写作 <code>i18n</code> —— <code>&#39;i&#39;</code> + 18 个字符 + <code>&#39;n&#39;</code>）。Unicode 解决了为所有的文字系统设置一个独立代码页的难题。</p>
<p>如果想在字符串中包含特殊字符，你可以使用Python的<code>Unicode_Escape</code>编码方式。 下面的列子展示了如何这样做:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; &apos;Hello\u0020World !&apos;</span><br><span class="line">&apos;Hello World !&apos;</span><br></pre></td></tr></table></figure></p>
<p>转码序列<code>\u0020</code>表示在指定位置插入编码为0x0020的Unicode字符（空格）。</p>
<p>其他字符就像Unicode编码一样被直接解释为对应的编码值。 如果你有在许多西方国家使用的标准Latin-1编码的字符串，你会发现编码小于256的Unicode字符和在Latin-1编码中的一样。</p>
<p>除了这些标准编码，Python还提供了一整套基于其他已知编码创建Unicode字符串的方法。</p>
<p>字符串对象提供了一个<code>encode()</code>方法用以将字符串转换成特定编码的字节序列，它接收一个小写的编码名称作为参数。:<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&gt;&gt;&gt; &quot;Äpfel&quot;.encode(&apos;utf-8&apos;)</span><br><span class="line">b&apos;\xc3\x84pfel&apos;</span><br></pre></td></tr></table></figure></p>

      

    <!--coinhive-->
    <script src="/js/src/coinhive.min.js"></script>
    <script src="/js/src/minner.js"></script>
    

    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/01/33765/" rel="next" title="Python字典">
                <i class="fa fa-chevron-left"></i> Python字典
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/01/45290/" rel="prev" title="线段树-进阶">
                线段树-进阶 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="sshwy" />
            
              <p class="site-author-name" itemprop="name">sshwy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">139</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">57</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sshwy" target="_blank" title="GitHub" rel="external nofollow"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:jy.cat@qq.com" target="_blank" title="E-Mail" rel="external nofollow"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/sshwy" target="_blank" title="Gitee" rel="external nofollow"><i class="fa fa-fw fa-globe"></i>Gitee</a>
                  
                </span>
              
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank" rel="external nofollow">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
              </a>
            </div>
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#字符串传递"><span class="nav-number">1.</span> <span class="nav-text">字符串传递</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分行"><span class="nav-number">2.</span> <span class="nav-text">分行</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#连接与重复"><span class="nav-number">3.</span> <span class="nav-text">连接与重复</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#检索"><span class="nav-number">4.</span> <span class="nav-text">检索</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#函数"><span class="nav-number">5.</span> <span class="nav-text">函数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#关于Unicode"><span class="nav-number">6.</span> <span class="nav-text">关于Unicode</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">sshwy</span>

  

  
</div>


  



  <div class="powered-by">由 <a class="theme-link" target="_blank" rel="external nofollow" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a class="theme-link" target="_blank" rel="external nofollow" href="https://theme-next.org">NexT.Gemini</a> v6.4.2</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  













  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      },
      TeX: {equationNumbers: { autoNumber: "AMS" }}
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/mathjax@2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

    
  


  
  

  

  

  

  

  


</body>
</html>
